<?php

namespace App\Http\Controllers\Guard\Order;

use App\Http\Controllers\Common\ApiController;
use App\Models\Constant\Constant;
use App\Models\Goods\Goods;
use App\Models\Order\Order;
use App\Models\Rbac\GuardUser;
use App\Models\User\PointLog;
use App\Models\User\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderController extends ApiController {

    public function __construct() {
        $this->instance = new Order();
    }


    public function lst(Request $request) {
        if ($request->has('all')) {
            $records = $this->instance->newQuery()->where('status', 1)
                ->where('num', '>', 0)
                ->get();
            return responseSuccess($records->toArray());
        }
        $page = $request->input('page', 1);
        $pageSize = $request->input('pageSize', 50);
        $conditions = $request->input();
        $records = $this->instance->getLst($conditions)->with(['getUser', 'getGoods'])->paginate($pageSize, $this->getCol, 'page', $page);
        return responseSuccess($records->items(), $records->total());

    }

    public function change(Request $request) {
        $id = $request->input('id', 0);
        $type = $request->input('type');
        $record = $this->instance->newQuery()->find($id);
        if ($type == 'finish') {
            $record->status = Constant::ORDER_STATUS_FINISH;
        } elseif ($type == 'cancel') {
            $record->status = Constant::ORDER_STATUS_CANCEL;
        } else {

        }
        $record->save();
        return responseSuccess();
    }


    public function add(Request $request) {
        $info = $request->input();
        $exchange_num = $request->input('exchange_num', 1);
        $userIds = $info['userIds'];
        $goodsId = $info['goodsId'];
        $goods = Goods::query()->find($goodsId);
        $need_point = $goods->point * $exchange_num;
        $this->validate($request, [

        ], [], [

        ]);

        $token = $request->header('token');
        $guardUserId = checkJWT($token)['id'];
        $guardUser = GuardUser::query()->find($guardUserId);

        try {
            DB::beginTransaction();
            foreach ($userIds as $userId) {
                $user = User::query()->find($userId);
                if ($user->point < $need_point) {
                    return responseFail("{$user->name}的积分不足！");
                }

                $order = $this->instance->newQuery()->create([
                    'user_id'      => $userId,
                    'goods_id'     => $goodsId,
                    'tel'          => $user->phone,
                    'status'       => Constant::ORDER_STATUS_FINISH,
                    'need_point'   => $need_point,
                    'address'      => '默认',
                    'exchange_num' => $exchange_num,
                    'type'         => 2,
                    'beizhu'       => '后台手动',
                ]);

                $user->point -= $need_point;
                $user->save();

                PointLog::query()->create([
                    'user_id'  => $userId,
                    'name'     => $user->name,
                    'passport' => $user->passport,
                    'phone'    => $user->phone,
                    'action'   => 'divi',
                    'point'    => $need_point,
                    'reason'   => "{$guardUser->name}后台手动下单,单号{$order->id}"
                ]);
            }
            DB::commit();
            return responseSuccess();
        } catch (\Exception $e) {
            DB::rollBack();
            $tip = $e->getFile() . ':' . $e->getLine() . ':' . $e->getMessage();
            return responseFail($tip);
        }
    }
}
